import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { fileURLToPath, URL } from 'node:url'
import { VitePWA } from 'vite-plugin-pwa'
import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'
import path from 'path'

// 路径别名配置
const pathAliases = {
  '@': fileURLToPath(new URL('./src', import.meta.url)),
  '@components': fileURLToPath(new URL('./src/components', import.meta.url)),
  '@views': fileURLToPath(new URL('./src/views', import.meta.url)),
  '@pages': fileURLToPath(new URL('./src/pages', import.meta.url)),
  '@data': fileURLToPath(new URL('./src/data', import.meta.url)),
  '@router': fileURLToPath(new URL('./src/router', import.meta.url)),
  'font-awesome': path.resolve(__dirname, './node_modules/font-awesome')
}

// PWA配置
const pwaOptions = {
  manifest: {
    name: '科技创客空间',
    short_name: '创客空间',
    description: '分享3D打印、电子DIY和软件开发的科技博客',
    theme_color: '#0f172a',
    background_color: '#0f172a',
    display: 'standalone',
    icons: [
      {
        src: '/icons/icon-192x192.png',
        sizes: '192x192',
        type: 'image/png'
      },
      {
        src: '/icons/icon-512x512.png',
        sizes: '512x512',
        type: 'image/png'
      }
    ]
  },
  workbox: {
    clientsClaim: true,
    skipWaiting: true,
    runtimeCaching: [
      {
        urlPattern: ({ request }) => request.destination === 'image',
        handler: 'CacheFirst',
        options: {
          cacheName: 'blog-images',
          expiration: {
            maxEntries: 60,
            maxAgeSeconds: 30 * 24 * 60 * 60 // 缓存30天
          }
        }
      }
    ]
  }
}

// 主配置
export default defineConfig({
  root: process.cwd(),

  server: {
    open: true,
    cors: true
  },

  plugins: [
    vue(),
    VitePWA(pwaOptions)
  ],

  resolve: {
    alias: pathAliases
  },
  // 确保字体文件被正确处理
  assetsInclude: ['**/*.woff', '**/*.woff2', '**/*.ttf'],
  // 关键修复：模拟global和process环境变量
  define: {
    'process.env': process.env || {},
    global: 'window', // 将global映射到window
  },

  optimizeDeps: {
    esbuildOptions: {
      plugins: [
        NodeGlobalsPolyfillPlugin({
          process: true,
          buffer: true,
          global: true // 启用global模拟
        })
      ]
    }
  },

  // 添加全局垫片
  esbuild: {
    jsxInject: `import { global } from '@/shims/global';`
  },

  build: {
    outDir: 'dist',
    assetsDir: 'assets',
    sourcemap: false,
    minify: 'esbuild',
    rollupOptions: {
      input: {
        main: fileURLToPath(new URL('./index.html', import.meta.url))
      },
      output: {
        chunkFileNames: 'assets/js/[name]-[hash].js',
        entryFileNames: 'assets/js/[name]-[hash].js',
        assetFileNames: 'assets/[ext]/[name]-[hash].[ext]'
      }
    }
  },

  preview: {
    port: 4000
  }
})
